//该文件用于创建Vuex中最为核心的store
import { reqGoodsInfo,reqAddToCart } from "@/api";
import { getUUID } from "@/utils/uuid_token";


//准备actions一用于响应组件中的动作
const actions = {
  async getGoodsInfo({ commit }, skuId) {
    let result = await reqGoodsInfo(skuId);
    if (result.code == 200) {
      commit("GETGOODSINFO", result.data);
    }
  },
  async addToCart({commit},{skuId,skuNum}){
    let result = await reqAddToCart(skuId,skuNum)
    if(result.code == 200){
        return "成功"
    }else{
        return Promise.reject(new Error('faile'))
    }
  }
};
//准备mutations.一用于操作数据(state)
const mutations = {
  GETGOODSINFO(state, goodsInfo) {
    state.goodsInfo = goodsInfo;
  },
};
//准备state一用于存储数据
const state = {
  goodsInfo: {},
  uuid_token:getUUID()
};
//getters:理解为计算属性，用于简化仓库数据，让组件获取仓库的数据更加方便
const getters = {
  categoryView(state) {
    let data = [];
    for (let name in state.goodsInfo.categoryView) {
      if (name.indexOf("N") != -1) {
        data.push(state.goodsInfo.categoryView[name]);
      }
    }
    return data;
  },
  skuInfo(state) {
    return state.goodsInfo.skuInfo || {};
  },
  skuImageList(state) {
    return state.goodsInfo.skuInfo.skuImageList || [];
  },
  spuSaleAttrList(state) {
    return state.goodsInfo.spuSaleAttrList;
  },
};

//创建并暴露store
export default {
  state,
  mutations,
  actions,
  getters,
};
